import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/model/user/user_model.dart';
import 'package:labcloud_app/api/graphql/order_gql.dart';
import 'package:labcloud_app/widget/async_image.dart';
import 'package:labcloud_app/model/order_model.dart';
import 'package:labcloud_app/data/order.dart';

class OrderMainPage extends StatefulWidget {
  const OrderMainPage({Key? key}) : super(key: key);

  @override
  State<OrderMainPage> createState() => _OrderMainPageState();
}

class _OrderMainPageState extends State<OrderMainPage> {
  String? status;
  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      final args = ModalRoute.of(context)?.settings.arguments;
      // 获取路由参数
      if (args != null && args is String) {
        status = args;
        print("路由参数: $args");
      }
      final client = GraphQLProvider.of(context).value;
      var orderModel = context.read<OrderModel>();
      await orderModel.loadOrders(client, status);
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  Future<void> _loadOrders() async {
    final client = GraphQLProvider.of(context).value;
    var orderModel = context.read<OrderModel>();
    await orderModel.loadOrders(client, status);
  }

  @override
  Widget build(BuildContext context) {
    final orderModel = Provider.of<OrderModel>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(
          orderModel.getStatusTitle(orderModel.getStatusTitle(status)),
        ),
        actions: [],
      ),
      body: Consumer<OrderModel>(
        builder: (context, orderModel, child) {
          if (orderModel.isLoading) {
            return Center(child: CircularProgressIndicator());
          }
          if (orderModel.errorMessage?.isNotEmpty == true) {
            return Center(child: Text('加载失败'));
          }
          if (orderModel.orderList.isEmpty) {
            return const Center(child: Text('暂无订单'));
          }
          return RefreshIndicator(
            onRefresh: () async {
              // 下拉刷新时重置加载状态并重新加载订单
              _loadOrders();
            },
            child: ListView.builder(
              itemCount: orderModel.orderList.length,
              itemBuilder: (context, index) {
                final order = orderModel.orderList[index];
                return _buildOrderItem(order, orderModel);
              },
            ),
          );
        },
      ),
    );
  }

  Widget _buildOrderItem(Order order, OrderModel orderModel) {
    return Card(
      margin: const EdgeInsets.all(10),
      child: Padding(
        padding: const EdgeInsets.all(15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 订单状态和编号
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '订单编号: ${order.id}',
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 10,
                    vertical: 5,
                  ),
                  decoration: BoxDecoration(
                    color: orderModel.getStatusColor(order.status),
                    borderRadius: BorderRadius.circular(15),
                  ),
                  child: Text(
                    orderModel.getStatusText(order.status),
                    style: const TextStyle(color: Colors.white, fontSize: 12),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 10),

            // 商品信息 - 根据商品数量决定显示方式
            GestureDetector(
              onTap: () {
                Navigator.pushNamed(context, '/order_detail', arguments: order);
              },
              child: _buildProductPreview(order.products),
            ),

            const SizedBox(height: 10),
            const Divider(),

            // 订单金额和操作按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '实付: ¥${order.realPrice}',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.red,
                  ),
                ),
                const SizedBox(width: 35),
                // 根据订单状态显示不同的按钮组合
                if (order.status == 'non_pay') ...[
                  // 未支付订单：显示取消订单和立即支付按钮
                  ElevatedButton(
                    onPressed: () => _cancelOrder(
                      orderModel,
                      order.id!,
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.grey,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('取消订单'),
                  ),
                  const SizedBox(width: 5),
                  ElevatedButton(
                    onPressed: () => _payOrder(
                      orderModel,
                      order.id!,
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('立即支付'),
                  ),
                ] else if (order.status == 'undelivered') ...[
                  // 未配送订单：显示模拟送达和取消订单按钮
                  ElevatedButton(
                    onPressed: () => _cancelOrder(
                      orderModel,
                      order.id!,
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.grey,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('取消订单'),
                  ),
                  const SizedBox(width: 5),
                  ElevatedButton(
                    onPressed: () => _deliverOrder(
                      orderModel,
                      order.id!,
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('模拟送达'),
                  ),
                ] else if (order.status == 'unconfirmed') ...[
                  // 未确认订单：显示确认收货和申请售后按钮
                  ElevatedButton(
                    onPressed: () => _applyAfterSales(
                      orderModel,
                      order.id!,
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.grey,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('申请售后'),
                  ),
                  const SizedBox(width: 5),
                  ElevatedButton(
                    onPressed: () => _confirmReceipt(
                      orderModel,
                      order.id!,
                    ),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue,
                      foregroundColor: Colors.white,
                    ),
                    child: const Text('确认收货'),
                  ),
                ],
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildProductPreview(List<Product>? products) {
    if (products == null || products.isEmpty) {
      return const SizedBox(); // 或者显示默认占位图
    }
    if (products.length == 1) {
      return _buildSingleProductItem(products.first);
    } else {
      return _buildMultipleProductItems(products);
    }
  }

  Widget _buildSingleProductItem(Product product) {
    return Row(
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(5),
          child: SizedBox(
            width: 60,
            height: 60,
            child: AsyncImageWidget(
              imageUrl: product.coverAddr ?? '',
              fit: BoxFit.cover,
            ),
          ),
        ),
        const SizedBox(width: 10),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                product.title ?? '',
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 5),
              Text('数量: ${product.quantity}'),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildMultipleProductItems(List<Product> products) {
    return Row(
      children: [
        // 显示前三个商品图片
        for (int i = 0; i < products.length && i < 3; i++) ...[
          if (i > 0) const SizedBox(width: 5),
          ClipRRect(
            borderRadius: BorderRadius.circular(5),
            child: SizedBox(
              width: 60,
              height: 60,
              child: AsyncImageWidget(
                imageUrl: products[i].coverAddr ?? '',
                fit: BoxFit.cover,
              ),
            ),
          ),
        ],
        // 如果超过三个商品，显示省略号
        if (products.length > 3) ...[
          const SizedBox(width: 5),
          const SizedBox(
            width: 60,
            height: 60,
            child: Center(
              child: Text(
                '...',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
            ),
          ),
        ],
      ],
    );
  }

  Future<void> _cancelOrder(OrderModel orderModel, String orderId) async {
    try {
      final client = GraphQLProvider.of(context).value;

      final result = await client.mutate(
        MutationOptions(
          document: gql(OrderGQL.fetchOrderCancel),
          variables: {'orderId': orderId},
        ),
      );

      if (result.hasException) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('取消订单失败: ${result.exception.toString()}')),
          );
        }
        return;
      }

      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('订单已取消')));
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('取消订单异常: $e')));
      }
    }
  }

  Future<void> _deliverOrder(OrderModel orderModel, String orderId) async {
    try {
      final client = GraphQLProvider.of(context).value;

      final result = await client.mutate(
        MutationOptions(
          document: gql(OrderGQL.fetchOrderDelivered),
          variables: {'orderId': orderId},
        ),
      );

      if (result.hasException) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('模拟送达失败: ${result.exception.toString()}')),
          );
        }
        return;
      }

      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('订单已送达')));
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('模拟送达异常: $e')));
      }
    }
  }

  Future<void> _confirmReceipt(OrderModel orderModel, String orderId) async {
    try {
      final client = GraphQLProvider.of(context).value;

      final result = await client.mutate(
        MutationOptions(
          document: gql(OrderGQL.fetchOrderConfirm),
          variables: {'orderId': orderId},
        ),
      );

      if (result.hasException) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('确认收货失败: ${result.exception.toString()}')),
          );
        }
        return;
      }

      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('确认收货成功')));
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('确认收货异常: $e')));
      }
    }
  }

  Future<void> _applyAfterSales(OrderModel orderModel, String orderId) async {
    if (mounted) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('申请售后功能待实现')));
    }
  }

  // 显示支付密码验证对话框
  void _showPaymentPasswordDialog({
    required BuildContext context,
    required void Function(String password) onSuccess,
    required VoidCallback onCancel,
  }) {
    final TextEditingController passwordController = TextEditingController();

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('输入支付密码'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('请输入6位数字支付密码'),
              const SizedBox(height: 15),
              TextField(
                controller: passwordController,
                keyboardType: TextInputType.number,
                obscureText: true,
                maxLength: 6,
                decoration: const InputDecoration(
                  hintText: '请输入支付密码',
                  border: OutlineInputBorder(),
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                onCancel();
              },
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                final password = passwordController.text;

                if (password.isEmpty) {
                  ScaffoldMessenger.of(
                    context,
                  ).showSnackBar(const SnackBar(content: Text('请输入支付密码')));
                  return;
                }

                if (password.length != 6 ||
                    !RegExp(r'^\d{6}$').hasMatch(password)) {
                  ScaffoldMessenger.of(
                    context,
                  ).showSnackBar(const SnackBar(content: Text('支付密码必须为6位数字')));
                  return;
                }

                onSuccess(password);
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  Future<void> _payOrder(OrderModel orderModel, String orderId) async {
    // 显示支付密码验证对话框
    _showPaymentPasswordDialog(
      context: context,
      onSuccess: (password) {
        Navigator.pop(context); // 关闭支付密码对话框
        _executePayOrder(orderModel, orderId, password);
      },
      onCancel: () {
        Navigator.pop(context); // 关闭支付密码对话框
      },
    );
  }

  Future<void> _executePayOrder(
      OrderModel orderModel,
      String orderId,
      String payPassword,
      ) async {
    try {
      final client = GraphQLProvider.of(context).value;

      final result = await client.mutate(
        MutationOptions(
          document: gql(OrderGQL.fetchOrderPay),
          variables: {'orderId': orderId, 'payPassword': payPassword},
        ),
      );

      if (result.hasException) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('支付失败: ${result.exception.toString()}')),
          );
        }
        return;
      }

      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('支付成功')));

        // 可以导航到支付成功页面
        // Navigator.of(context).pushNamed('/payment_success');
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('支付异常: $e')));
      }
    }
  }
}
